package com.ljx.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.ljx.common.AppHttpCodeEnum;
import com.ljx.common.ResponseResult;
import com.ljx.domain.entity.Category;
import com.ljx.domain.vo.CategoryVo;
import com.ljx.domain.vo.ExcelCategoryVo;
import com.ljx.loginConfig.WebUtils;
import com.ljx.service.CategoryService;
import com.ljx.service.RoleService;
import com.ljx.utils.BeanCopyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 李捷禧
 * Date: 2023/4/21
 * ClassName: CategoryController
 */

@RestController
@RequestMapping("/content/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list")
    public ResponseResult list(Integer pageNum, Integer pageSize,String name,String status){
       return categoryService.listAll(pageNum,pageSize,name,status);
    }

    @PostMapping
    public ResponseResult add(@RequestBody Category category){
        categoryService.save(category);
        return ResponseResult.okResult("添加成功");
    }

    @GetMapping("{id}")
    public ResponseResult getOne(@PathVariable Long id){
        Category category = categoryService.getById(id);
        return ResponseResult.okResult(category);
    }

    @PutMapping
    public ResponseResult update(@RequestBody Category category){
        categoryService.updateById(category);
        return ResponseResult.okResult("修改成功");
    }

    @DeleteMapping("{id}")
    public ResponseResult delete(@PathVariable List<Long> id){
        categoryService.removeByIds(id);
        return ResponseResult.okResult("删除成功");
    }

    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory(){
        List<CategoryVo> list = categoryService.listAllCategory();
        return ResponseResult.okResult(list);
    }

    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("分类.xlsx",response);
            //获取需要导出的数据
            List<Category> categoryVos = categoryService.list();

            List<ExcelCategoryVo> excelCategoryVos = BeanCopyUtils.copyBeanList(categoryVos, ExcelCategoryVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), ExcelCategoryVo.class).autoCloseStream(Boolean.FALSE).sheet("分类导出")
                    .doWrite(excelCategoryVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }


}
